<?php
/**
 * 内容管理
 *
 * @package         YDCMS
 * @author          QQ:644157559 <644157559@qq.com>
 * @version         $Id: ContentController.class.php v1.0 2014-06-12 17:27:03 $
 */
namespace Admin\Controller;
class ContentController extends CommonController{
    private $model;
    private $service;
    public function _initialize() {
        parent::_initialize();
        $this->model = D("Content");
        $this->service = D("Content", "Service");
        $data['attlist'] = M("Conatt")->order("sortid asc")->select();
        $data['up_salt'] = salt();
        $data['up_token'] = md5(C("COOKIE_ENCODE") . $data['up_salt']);
        //var_dump($_SESSION, $_COOKIE);die;
        $this->assign($data);
    }
    
    /**
     * 文档列表
     */
    public function index() {
        $modelid = I("get.id", 0, "intval");//模型ID
        $typeid = I("get.cid", 0, "intval");//栏目ID
        $data["param"] = array();
        $where = array();
        if($modelid > 0){
            $where['mid'] = $modelid;
            $data["param"]["id"] = $modelid;
        }
        if($typeid > 0){
            $where['typeid'] = $typeid;
            $data["param"]["tid"] = $typeid;
        }
        $result = $this->getPagination("Content", $where);
        $this->assign('ContentList', $result['data']);
        $this->assign('ContentCount', $result['total_rows']);
        $this->assign('page', $result['show']);
        $this->assign($data);
        $this->display();
    }
    
    /**
     * 添加文档
     */
    public function add() {
        $modelid = I("get.id", 1, "intval");//模型ID
        $typeid = I("get.tid", 0, "intval");//栏目ID
        if($typeid > 0){
            $type_info = D("Contype", "Service")->getById($typeid);
            if(!isArrayAndNotEmpty($type_info)){
                $this->error("无效操作！");
            }
            if($type_info['model_id'] != $modelid){
                $modelid = $type_info['model_id'];
            }
        }else{
            if($modelid <= 0){
                $modelid = 1;
            }
        }
        $model_info = D("Model", "Service")->getById($modelid);
        //var_dump($model_info);die;
        if(!isArrayAndNotEmpty($model_info)){
            $this->error("无法识别模型信息，因此无法操作！");
        }
        $types = D("Contype", "Service")->getTypes(array('model_id' => $modelid, "ispart" => array("neq", 2)));
        //var_dump($types);die;
        $data['addfields'] = D("Field", "Service")->getByModelId($modelid, "*", 1);
        $data['mid'] = $modelid;
        $data['nid'] = $model_info["nid"];
        $data['tid'] = $typeid;
        $data['types'] = $types;
        $this->assign($data);
        $this->display();
    }
    /**
     * 创建文档
     */
    public function create() {
        $content = I("post.content");
        $addTableData = I("post.addtable");
        
        if(intval($content['typeid']) == 0){
            $this->errorReturn("请指定文档的栏目！");
        }
        if(intval($content['mid']) == 0){
            $this->errorReturn("文档为非指定的类型，请检查你发布内容的表单是否合法！");
        }
        $type = D("Contype", "Service")->getById($content['typeid']);
        if(!isArrayAndNotEmpty($type)){
            $this->errorReturn("您选择的栏目不存在！");
        }else{
            $content['lang'] = $type['lang'];
        }
        if(!D("Contype", "Service")->CheckModel($content['typeid'], $content['mid']))
        {
            $this->errorReturn("你所选择的栏目与当前模型不相符，请选择白色的选项！");
        }
        $content["flag"] = !empty($content["flag"]) ? join(",", $content["flag"]) : '';
        
        //处理图片文档的自定义属性
        if($content["litpic"] != '' && !preg_match("#p#", $content["flag"]))
        {
            $content["flag"] = ($content["flag"]=='' ? 'p' : $content["flag"].',p');
        }
        if($addTableData["redirecturl"] != '' && !preg_match("#j#", $content["flag"]))
        {
            $content["flag"] = ($content["flag"]=='' ? 'j' : $content["flag"].',j');
        }

        //跳转网址的文档强制为动态
        if(preg_match("#j#", $content["flag"])){$content["ismake"] = 0;}

        $model_info = D("Model", "Service")->getById($content["mid"]);
        if(!isArrayAndNotEmpty($model_info)){
            $this->error("无法识别模型信息，因此无法操作！");
        }
        $addtable = $model_info['addtable'];
        $addTableData['body'] = AnalyseHtmlBody($addTableData['body'], $content["description"]);
        if(isset($addTableData['imgurls'])){
            $imgurls = array();
            for($i=0; $i<count($addTableData['imgurls']); $i++){
                $imgurls[$i]['imgurl'] = $addTableData['imgurls'][$i];
                $imgurls[$i]['imgtext'] = $addTableData['imgtext'][$i];
            }
            if(isArrayAndNotEmpty($imgurls)){
                $addTableData['imgurls'] = serialize($imgurls);
            }else{
                $addTableData['imgurls'] = '';
            }
        }
        $result = $this->service->add($content);
        if(!$result["status"]){
            return $this->errorReturn($result["data"]['error']);
        }
        
        $aid = $result["data"];
        $yd_addonfields = I("post.yd_addonfields");
        if(!empty($yd_addonfields))
        {
            $addonfields = explode(';', $yd_addonfields);
            if(is_array($addonfields))
            {
                foreach($addonfields as $v)
                {
                    if($v==''){
                        continue;
                    }
                    $vs = explode(',', $v);
                    if(!isset($addTableData[$vs[0]]))
                    {
                        $addTableData[$vs[0]] = '';
                    }
                    else if($vs[1]=='htmltext') //HTML文本特殊处理
                    {
                        $addTableData[$vs[0]] = AnalyseHtmlBody($addTableData[$vs[0]], $content["description"], $vs[1]);
                    }else{
                        if(!isset($addTableData[$vs[0]])){
                            $addTableData[$vs[0]] = '';
                        } 
                        $addTableData[$vs[0]] = GetFieldValueA($addTableData[$vs[0]], $vs[1]);
                    }
                }
            }
        }
        $addTableData["aid"] = $aid;
        $addTableData["typeid"] = $content["typeid"];
        $addTableData["userip"] = get_client_ip();
        //var_dump($addTableData);die;
        $result = $this->service->addTableData($addtable, $addTableData);
        if(!$result["status"]){
            
            return $this->errorReturn($result["data"]['error']);
        }
        return $this->successReturn('添加文档成功！', U('index', array("id" => $content["mid"])));
    }
    /**
     * 修改文档
     */
    public function edit() {
        $aid = I("get.aid", 0, "intval");
        if($aid <= 0){
            $this->error("无效操作！");
        }
        $content = $this->service->getById($aid);
        if(!isArrayAndNotEmpty($content)){
            $this->error("读取主表信息失败！");
        }
        $model_info = D("Model", "Service")->getById($content['mid']);
        if(!isArrayAndNotEmpty($model_info)){
            $this->error("读取模型配置信息出错！");
        }
        $addTableData = $this->service->getAddtableData($model_info['addtable'], $aid);
        if(!isArrayAndNotEmpty($addTableData)){
            $this->error("读取附表信息失败！");
        }
        if(isset($addTableData["imgurls"])){
            $addTableData["imgurls"] = unserialize($addTableData["imgurls"]);
        }
        $types = D("Contype", "Service")->getTypes(array('model_id' => $content['mid']));
        $data['aid'] = $aid;
        $data['mid'] = $content['mid'];
        $data['content'] = $content;
        $data['addRow'] = $addTableData;
        $data['nid'] = $model_info["nid"];
        $data['types'] = $types;
        $data['addfields'] = D("Field", "Service")->getByModelId($content['mid'], "*", 1);
        
        //var_dump($addTableData);die;
        $this->assign($data);
        $this->display();
    }
    /**
     * 更新文档
     */
    public function update() {
        $content = I("post.content");
        $addTableData = I("post.addtable");
        
        if(intval($content['typeid']) == 0){
            $this->errorReturn("请指定文档的栏目！");
        }
        if(intval($content['mid']) == 0){
            $this->errorReturn("文档为非指定的类型，请检查你发布内容的表单是否合法！");
        }
        $type = D("Contype", "Service")->getById($content['typeid']);
        if(!isArrayAndNotEmpty($type)){
            $this->errorReturn("您选择的栏目不存在！");
        }else{
            $content['lang'] = $type['lang'];
        }
        if(!D("Contype", "Service")->CheckModel($content['typeid'], $content['mid']))
        {
            $this->errorReturn("你所选择的栏目与当前模型不相符，请选择白色的选项！");
        }
        
        $model_info = D("Model", "Service")->getById($content["mid"]);
        if(!isArrayAndNotEmpty($model_info)){
            $this->error("无法识别模型信息，因此无法操作！");
        }
        $addtable = $model_info['addtable'];
        $addTableData['body'] = AnalyseHtmlBody($addTableData['body'], $content["description"]);
        if(isset($addTableData['imgurls'])){
            $imgurls = array();
            for($i=0; $i<count($addTableData['imgurls']); $i++){
                $imgurls[$i]['imgurl'] = $addTableData['imgurls'][$i];
                $imgurls[$i]['imgtext'] = $addTableData['imgtext'][$i];
            }
            if(isArrayAndNotEmpty($imgurls)){
                $addTableData['imgurls'] = serialize($imgurls);
            }else{
                $addTableData['imgurls'] = '';
            }
            $delimgurls = I("post.delimgurls");
            if(isset($delimgurls)){
                foreach ($delimgurls as $file) {
                    if(!preg_match("#[\\|/]Public[\\|/]uploads#", $file)){
                        continue;
                    }

                    if(!file_exists($file)){
                        continue;
                    }
                    RmRecurse($file);
                }
            }
        }else{
            $addTableData['imgurls'] = "";
        }
        $content["flag"] = !empty($content["flag"]) ? join(",", $content["flag"]) : '';
        
        //处理图片文档的自定义属性
        if($content["litpic"] != '' && !preg_match("#p#", $content["flag"]))
        {
            $content["flag"] = ($content["flag"]=='' ? 'p' : $content["flag"].',p');
        }
        if($addTableData["redirecturl"] != '' && !preg_match("#j#", $content["flag"]))
        {
            $content["flag"] = ($content["flag"]=='' ? 'j' : $content["flag"].',j');
        }

        //跳转网址的文档强制为动态
        if(preg_match("#j#", $content["flag"])){$content["ismake"] = 0;}
        $result = $this->service->update($content);
        if(!$result["status"]){
            return $this->errorReturn($result["data"]['error']);
        }
        $aid = $result["data"];
        $yd_addonfields = I("post.yd_addonfields");
        if(!empty($yd_addonfields))
        {
            $addonfields = explode(';', $yd_addonfields);
            if(is_array($addonfields))
            {
                foreach($addonfields as $v)
                {
                    if($v==''){
                        continue;
                    }
                    $vs = explode(',', $v);
                    
                    if(!isset($addTableData[$vs[0]])){
                        $addTableData[$vs[0]] = '';
                    }
                    $addTableData[$vs[0]] = GetFieldValueA($addTableData[$vs[0]], $vs[1]);
                }
            }
        }
        $addTableData["aid"] = $aid;
        $addTableData["typeid"] = $content["typeid"];
        
        $result = $this->service->upAddTableData($addtable, $addTableData);
        if(!$result["status"]){
            return $this->errorReturn($result["data"]['error']);
        }
        return $this->successReturn('修改文档成功！', U('index', array("id" => $content["mid"])));
    }
    
    /**
     * 删除文档
     */
    public function delete() {
        $act = I("post.act", "one");
        if($act == "one"){
            $aid = I("post.aid", 0, "intval");
            if($aid <= 0){
                return $this->errorReturn("无效操作！");
            }
            $content = $this->service->getById($aid);
            if(!isArrayAndNotEmpty($content)){
                return $this->errorReturn("您要删除的数据不存在！");
            }
            $model_info = D("Model", "Service")->getById($content["mid"]);
            if(!isArrayAndNotEmpty($model_info)){
                $this->error("无法识别模型信息，因此无法操作！");
            }
            $addtable = $model_info['addtable'];
            if(false === $this->service->delete($aid)){
                $this->error("删除数据失败！");
            }else{
                $this->service->deleteAddTable($addtable, $aid);
            }
            return $this->successReturn('删除数据成功！', U('index'));
        }else if($act == "two"){
            $aids = I("post.aids");
            if(!isArrayAndNotEmpty($aids)){
                return $this->errorReturn("无效操作！");
            }
            foreach ($aids as $aid) {
                $content = $this->service->getById($aid);
                if(!isArrayAndNotEmpty($content)){
                    return $this->errorReturn("您要删除的数据不存在！");
                }
                $model_info = D("Model", "Service")->getById($content["mid"]);
                if(!isArrayAndNotEmpty($model_info)){
                    $this->error("无法识别模型信息，因此无法操作！");
                }
                $addtable = $model_info['addtable'];
                $this->service->delete($aid);
                $this->service->deleteAddTable($addtable, $aid);
            }
            
            return $this->successReturn('删除数据成功！', U('index'));
        }else{
            return $this->errorReturn("无效操作！");
        }
    }
    
    /**
     * 设置属性
     */
    public function setFlag() {
        $aids = I("post.aids");
        if(!isArrayAndNotEmpty($aids)){
            return $this->errorReturn("无效操作！");
        }
        $type = I("post.type", NULL);
        $falgatt = I("post.falgatt", NULL);
        
        if(empty($type)){
            return $this->errorReturn("无效操作！");
        }
        if(empty($falgatt)){
            return $this->errorReturn("必须指定要添加的属性！");
        }
        
        $result = $this->service->getAll(array("id" => array("in", $aids)));
        if($type == 'add'){
            foreach ($result as $val) {
                $flag = ($val['flag']=='' ? $falgatt : $val['flag'].','.$falgatt);
                $this->model->where("id={$val['id']}")->setField('flag', $flag);
            }
            return $this->successReturn("成功对选中文档增加指定的属性！");
        }else if ($type == 'del') {
            foreach ($result as $val) {
                
                if(trim($val['flag'])=='' || !preg_match("#".$falgatt."#", $val['flag']) ){
                    continue;
                }
                else
                {
                    $flags = explode(',', $val['flag']);
                    $okflags = array();
                    foreach($flags as $f)
                    {
                        if($f != $falgatt){
                             $okflags[] = $f;
                        }
                    }
                }
                $flag = trim(join(',', $okflags));
                $this->model->where("id={$val['id']}")->setField('flag', $flag);
            }
            return $this->successReturn("成功对选中文档删除指定的属性！");
        }else{
            return $this->errorReturn("无效操作！");
        }
    }
}
